package com.zhkj.txg.module.home.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.BaseResponse
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.module.home.entity.EventResponse
import com.zhkj.txg.module.home.entity.SearchProductResponse
import com.zhkj.txg.module.home.entity.TopDataResponse
import com.zhkj.txg.module.home.entity.TopProductResponse
import com.zhkj.txg.module.home.model.HomeManager

class EventCommodityViewModel(application: Application) : BaseViewModel(application) {
    private val homeManager = HomeManager()
    val eventLiveData = MutableLiveData<HttpResponse<EventResponse>>()
    val addCartLiveData = MutableLiveData<HttpResponse<BaseResponse>>()
    val productListLiveData = MutableLiveData<HttpResponse<SearchProductResponse>>()

    fun getGoodsActivity(token: String, id: Int) {
        val listener = object : ViewModelSubscribeListener<EventResponse>(eventLiveData) {
            override fun onSuccess(resp: EventResponse) {
                super.onSuccess(resp)
            }
        }
        val topData = homeManager.getGoodsActivity(token, id, listener)
        dispose.add(topData)
    }

    private val numb = 20
    var page = 1
        private set

    fun searchProduct(activeType: Int, restart: Boolean = false) {
        val listener = object :
            ViewModelSubscribeListener<SearchProductResponse>(productListLiveData) {
            override fun onSuccess(resp: SearchProductResponse) {
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (restart) page = 1
        val searchProduct = homeManager.searchProduct(
            token = AccountManager.getToken(),
            shopId = CustomApplication.getShopId(),
            activeType = if (activeType == 0) 0 else 1,
            search = null,
            catId = 0,
            sort = "weigh",
            sortAsc = "desc",
            page = page.toString(),
            rows = numb.toString(),
            recommend = if (activeType == 0) 1 else null,
            listener = listener
        )
        dispose.add(searchProduct)
    }

    /**
     * 添加购物车
     */
    fun addCart(map: Map<String, String>) {
        val listener = ViewModelSubscribeListener(addCartLiveData)
        val addCart = homeManager.addCart(map, listener)
        dispose.add(addCart)
    }
}